<template>
  <!-- 充值卡明细 -->
  <div class="app-page">
    <div class="top-info">
      <div class="top-info-box">
        <el-card shadow="never">
          <img :src="image">
          <div style="line-height: 40px;">
            <p>累计充值会员</p>
            <div class="text">{{ infoData.totalCsmNum }}<span>人</span></div>
          </div>
        </el-card>
      </div>
      <div class="top-info-box">
        <el-card shadow="never">
          <img :src="price">
          <div style="line-height: 40px;">
            <p>累计充值金额(含赠送)</p>
            <div class="text">{{ numberFormat1(infoData.totalCardAndSendMoney) }}<span>元</span></div>
          </div>
        </el-card>
      </div>
      <div class="top-info-box">
        <el-card shadow="never">
          <img :src="price">
          <div style="line-height: 40px;">
            <p>累计消费金额</p>
            <div class="text">{{ numberFormat1(infoData.totalPayMoney) }}<span>元</span></div>
          </div>
        </el-card>
      </div>
      <div class="top-info-box">
        <el-card shadow="never">
          <img :src="price">
          <div style="line-height: 40px;">
            <p>剩余充值金额(含赠送)</p>
            <div class="text">{{ numberFormat1(infoData.cashAndSendMoney) }}<span>元</span></div>
          </div>
        </el-card>
      </div>
    </div>
    <div class="table">
      <el-table-form ref="form">
        <el-form-item class="merge-item">
          <el-select v-model="qtype" style="width: 180px; margin-right: 2px;">
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户名称" value="csmName" />
            <el-option label="客户组号" value="csmCode1" />
            <el-option label="客户组名称" value="csmName1" />
            <el-option label="充值卡号" value="cardCode" />
            <el-option label="电话" value="csmPhone" />
          </el-select>
          <el-input v-model.trim="qtTxt" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="开卡机构:">
          <el-tree-select
            v-model="query.orgId"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: false,
              placeholder: '请选择开卡机构',
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgId',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
          />
        </el-form-item>
        <el-form-item label="使用门店:">
          <el-tree-select
            v-model="query.useOrgId"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: false,
              placeholder: '请选择使用门店',
            }"
            :tree-params=" {
              'expand-on-click-node': false,
              'highlight-current': true,
              props:{
                value:'orgId',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData
            }"
          />
        </el-form-item>
        <el-form-item label="开卡日期:" :table-form-merge="2">
          <el-date-picker
            v-model="date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            unlink-panels
          />
        </el-form-item>
        <el-form-item label="卡状态:">
          <el-select v-model="query.cardStatus" clearable>
            <el-option label="激活" :value="2" />
            <el-option label="注销" :value="-1" />
            <el-option label="冻结" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="主副卡:">
          <el-select v-model="query.isMainCard" clearable>
            <el-option v-for="(item,index) in cardType" :key="index" :label="item.desc" :value="item.value" />
          </el-select>
        </el-form-item>
        <template v-slot:btns>
          <el-button v-permission="[90402, 1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 10px;">
        <div>
          <el-button v-permission="[90402, 2]" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
          <el-button v-permission="[90402, 3]" type="primary" @click="updateData">更新数据</el-button>
        </div>
      </div>
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{bottomOffset:10}"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        custom-column
        :row-class-name="seRowClass"
        @fetch="fetchData"
      />
    </div>
    <crad-info ref="cradInfo" :tree-data="treeData" :deal-map="dealMap" />
    <csm-detail
      ref="csmDetail"
      :parent-fetch-data="search"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
  </div>
</template>

<script>
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { queryMap, topUpAdministrationInfoList, topUpAdministrationInfoInfo, exportCsmcard, queryExportDomain, updateAutoChargeCard } from '@/api'
  import moment from 'dayjs'
  import CradInfo from './components/CradInfo.vue'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'

  export default {
    name: 'refil-card-detail',
    components: {
      CradInfo,
      CsmDetail
    },
    props: {
      treeData: {
        type: Array,
        required: true
      },
      dealMap: {
        type: Array,
        required: true
      },
      infoData: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        image: require('@/assets/person.jpg'),
        price: require('@//assets/price.jpg'),
        query: {
          cardStatus: 2,
          orgId: '',
          isMainCard: '',
          useOrgId: ''
        },
        qtTxt: '',
        qtype: 'csmCode',
        date: [],
        calcTypeList: [],
        paymenFilList: [],
        tableData: {
          total: 0,
          data: []
        },
        cardType: [
          {
            desc: '全部',
            value: ''
          },
          {
            desc: '主卡',
            value: 1
          },
          {
            desc: '副卡',
            value: 2
          }
        ]
      }
    },
    computed: {
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          {
            prop: 'cardCode',
            label: '充值卡号',
            width: 150,
            render: (h, { row }) => (
              row.cardCode ? <el-link underline={false} onClick={() => this.csmcardDetail(row)}>
                {row.cardCode}
              </el-link> : <span>{row.cardCode}</span>
            )
          },
          {
            prop: 'cardStatus',
            label: '充值卡状态',
            width: 150,
            render: (h, { row }) => <span>{row.cardStatus && this.filtersType(row.cardStatus) }</span>
          },
          {
            prop: 'isMainCard',
            label: '主副卡',
            render: (h, { row }) => (
            <span>
              {row.isMainCard
                ? formatColumnMap(this.cardType, 'value', row.isMainCard, 'desc')
                : ''}
            </span>
          )
          },
          {
            prop: 'csmCode',
            label: '绑定客户编号/组号',
            width: 150,
            render: (h, { row }) => (
              row.csmCode && row.cardOpenStatus === 1 ? <el-link underline={false} onClick={() => this.openCsm(row)}>
                {row.csmCode}
              </el-link> : <span>{row.csmCode}</span>
            )
          },
          {
            prop: 'csmName',
            label: '绑定客户名称/组名称',
            width: 150
          },
          {
            prop: 'csmPhone',
            label: '绑定客户电话',
            width: 150
          },
          {
            prop: 'createTime',
            label: '开卡时间',
            width: 180,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'cardSurplus',
            label: '卡余额（元）',
            width: 150,
            render: (h, { row }) => <span>{row.cardSurplus && this.numberFormat(row.cardSurplus, row)}</span>
          },
          {
            prop: 'createUser',
            label: '开卡人',
            width: 100
          },
          {
            prop: 'orgName',
            label: '开卡机构',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'useOrgName',
            label: '使用门店',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'refundRemark',
            label: '备注',
            render: (h, { row }) => <span>{row.refundRemark && this.chooseFormat(row.refundRemark, row)}</span>
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            width: 130,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {(row.cardStatus === -1 || row.cardStatus === 2) && <el-link size='mini' underline={false} onClick={() => this.csmcardDetail(row, $index)}>充值卡详情</el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      this.getExportDomain()
      this.queryOptionsMap()
    },
    methods: {
      // 查询字典枚举
      async queryOptionsMap() {
        const [res4, res5] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' })
        ])
        this.calcTypeList = res4.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res5.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.paymentMethodMap = res5.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
      },
      async fetchData({ currentPage, pageSize }) {
        const params = {
          ...this._getQuery(this.query),
          pageIndex: currentPage,
          pageSize
        }
        if (this.qtTxt) {
          if (this.qtype === 'csmCode1' || this.qtype === 'csmName1') {
            params.csmCode = this.qtTxt
            params.cardOpenStatus = 2
          } else if (this.qtype === 'csmCode' || this.qtype === 'csmName') {
            params[this.qtype] = this.qtTxt
            params.cardOpenStatus = 1
          } else {
            params[this.qtype] = this.qtTxt
          }
        }
        if (this.date && this.date.length === 2) {
          params.startTime = moment(this.date[0]).format()
          params.endTime = moment(this.date[1]).format()
        } else {
          params.startTime = null
          params.endTime = null
        }
        const res = await topUpAdministrationInfoList(params)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 打开客户
      async openCsm(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 充值卡详情
      async csmcardDetail(row) {
        const { data } = await topUpAdministrationInfoInfo({ cardCode: row.cardCode })
        await this.$refs.cradInfo.open(data)
      },
      async upDataCheckTable() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 清除对象空属性
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 查询
      async search() {
        await this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 导出
      async exportFile() {
        this.$confirm('确定导出数据？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          var list = JSON.parse(JSON.stringify(this.column))
          list.pop()
          list.shift()
          const value = {}
          await list.forEach(l => {
            value[l.prop] = l.label
            return value
          })
          const params = {
            ...this._getQuery(this.query)
          }
          if (this.qtTxt) {
            if (this.qtype === 'csmCode1' || this.qtype === 'csmName1') {
              params.csmCode = this.qtTxt
              params.cardOpenStatus = 2
            } else if (this.qtype === 'csmCode' || this.qtype === 'csmName') {
              params[this.qtype] = this.qtTxt
              params.cardOpenStatus = 1
            } else {
              params[this.qtype] = this.qtTxt
            }
          }
          if (this.date && this.date.length === 2) {
            params.startTime = moment(this.date[0]).format()
            params.endTime = moment(this.date[1]).format()
          } else {
            params.startTime = null
            params.endTime = null
          }
          const query = {
            paramInfo: {
              json: params
            },
            kv: value
          }
          await exportCsmcard(query).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 更新数据
      async updateData() {
        const res = await updateAutoChargeCard()
        if (res.data > 0) {
          this.$message.success('更新成功')
        } else {
          this.$message.warning('未查询到银行账单，请稍后再试')
        }
      },
      // 充值卡状态
      filtersType(v) {
        if (v === -1) {
          return '注销'
        } else if (v === 1) {
          return '待审核'
        } else if (v === 2) {
          return '激活'
        } else if (v === 3) {
          return '冻结'
        }
      },
      // 卡余额（元）
      numberFormat(val, r) {
        var rcType = r.rcType // 为1表示余额 为2表示次数
        if (rcType === 1) {
          val = val * 1.00 / 100
        }
        val = Number(val)
        if (rcType === 1) {
          val = isNaN(val) ? '0.00' : val.toFixed(2)
          return val + ' 元'
        } else if (rcType === 2) {
          return val + ' 次'
        } else {
          return ''
        }
      },
      // 选择展示备注信息 如果是退款销卡,当前备注信息是退款销卡备注 如果是冻结卡 当前备注信息是最后一条冻结卡备注信息
      chooseFormat(val, r) {
        var cardStatus = r.cardStatus // 为1表示余额 为2表示次数
        if (cardStatus === -1 && r.refundRemark !== undefined) {
          return r.refundRemark
        } else {
          if (r.freezeRemark !== undefined) {
            return r.freezeRemark
          }
        }
      },
      // 充值金额
      numberFormat1: function(val) {
        val = val * 1.00 / 100
        val = Number(val)
        val = isNaN(val) ? '0.00' : val.toFixed(2)
        return val
      },
      seRowClass({ row, rowIndex }) {
        if (row.cardStatus === -1) return 'red-bg-row'
      }
    }
  }
</script>

<style lang="scss" scoped>
.top-info {
  display: flex;
  // justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  .top-info-box {
    width: 290px;
    height: 105px;
    padding-right: 20px;
    /deep/.el-card__body {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 105px;
    }
    img {
      width: 53px;
      height: 53px;
      background: #01999f;
      border-radius: 6px;
    }
    p {
      font-family: PingFang SC, PingFang SC-Bold;
      font-size: 16px;
      font-weight: 700;
      color: #01999f;
    }
    .text {
      display: block;
      font-family: PingFang SC, PingFang SC-Bold;
      font-size: 22px;
      font-weight: 700;
      color: #353c4e;
      text-align: right;
    }
    span {
      font-size: 14px;
    }
  }
}
</style>
